package com.ge.chapter03webflux.simple;


import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Demo {

    public static void main(String[] args) throws IOException {

        // 创建一个能处理Http请求的处理器
        HttpHandler httpHandler = (ServerHttpRequest request,
                                   ServerHttpResponse response) -> {

            System.out.println("请求进入：" + request.getURI());

            // 用于创建响应数据的DataBuffer
            DataBufferFactory bufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = bufferFactory.wrap(("accept: " + request.getURI()).getBytes());

            return response.writeWith(Mono.just(dataBuffer));
        };

        // 启动一个服务器，接收请求
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        // 启动Netty服务器
        HttpServer.create()
                // 监听ip和端口
                .host("localhost")
                .port(8080)
                // 用指定的处理器处理请求
                .handle(adapter)
                .bindNow();

        System.out.println("服务器已启动");
        // 添加一个控制台读入，保持线程不结束
        System.in.read();
        System.out.println("服务器停止");
    }
}
